const state = {
  count: 666,
  cartList: JSON.parse(localStorage.getItem('cart') || '[]')
}

const mutations = {
  'ADD_CART'(state, goodsInfo) {
    let flag = false
    state.cartList.some(item => {
      if (item.id === goodsInfo.id) {
        item.count += goodsInfo.count
        flag = true
      }
    })
    // 加入购物车
    if (!flag) {
      state.cartList.push(goodsInfo)
    }
    // 把购物车的数据存到本地中
    localStorage.setItem('cart', JSON.stringify(state.cartList))
  },
  'TOGGLE_CHECKED'(state, val) {
    state.cartList.forEach(item => {
      item.isCompleted = val
    })
  }
}

const actions = {

}

const getters = {
  getAllCount(state) {
    let c = 0
    state.cartList.forEach(item => {
      c += item.count
    })
    return c
  },
  getAllPrice(state) {
    let p = 0
    state.cartList.forEach(item => {
      if (item.isCompleted) {
        p += item.price * item.count
      }
    })
    return p
  },
  checkboxAll(state) {
    return state.cartList.every(item => item.isCompleted)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}